using EasyAdmin.Admin.Application.Services;
using EasyAdmin.Admin.Entity.Entities;
using EasyAdmin.Admin.Entity.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace EasyAdmin.Admin.WebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class SysMenuController : ControllerBase
    {
        private readonly ISysMenuService _menuService;

        public SysMenuController(ISysMenuService menuService)
        {
            _menuService = menuService;
        }

        /// <summary>
        /// 获取菜单树形结构
        /// </summary>
        [HttpGet("tree")]
        public async Task<ApiResult<object>> GetMenuTree(long? userId = null)
        {
            // 如果没有指定userId，从JWT token中获取当前用户ID
            if (!userId.HasValue)
            {
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (long.TryParse(userIdClaim, out var currentUserId))
                {
                    userId = currentUserId;
                }
            }
            
            var menuTree = await _menuService.GetMenuTreeAsync(userId);
            return ApiResult<object>.Ok(menuTree);
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ApiResult<object>> GetMenuList([FromQuery] string keyword)
        {
            var menus = await _menuService.GetMenuListAsync(keyword);
            return ApiResult<object>.Ok(menus);
        }

        /// <summary>
        /// 获取菜单详情
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ApiResult<SysMenu>> GetMenu(int id)
        {
            var menu = await _menuService.GetMenuByIdAsync(id);
            if (menu == null)
                return ApiResult<SysMenu>.NotFound("菜单不存在");

            return ApiResult<SysMenu>.Ok(menu);
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        [HttpPost]
        public async Task<ApiResult> CreateMenu([FromBody] SysMenu menu)
        {
            var result = await _menuService.CreateMenuAsync(menu);
            if (!result.Success)
                return ApiResult.Fail(result.Message);

            return ApiResult.Ok(result.Message);
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        [HttpPut("{id}")]
        public async Task<ApiResult> UpdateMenu(int id, [FromBody] SysMenu menu)
        {
            if (id != menu.Id)
                return ApiResult.BadRequest("菜单ID不匹配");

            var result = await _menuService.UpdateMenuAsync(menu);
            if (!result.Success)
                return ApiResult.Fail(result.Message);

            return ApiResult.Ok(result.Message);
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<ApiResult> DeleteMenu(int id)
        {
            var result = await _menuService.DeleteMenuAsync(id);
            if (!result.Success)
                return ApiResult.Fail(result.Message);

            return ApiResult.Ok(result.Message);
        }

        /// <summary>
        /// 获取角色菜单ID列表
        /// </summary>
        [HttpGet("role/{roleId}")]
        public async Task<ApiResult<object>> GetRoleMenuIds(int roleId)
        {
            var menuIds = await _menuService.GetRoleMenuIdsAsync(roleId);
            return ApiResult<object>.Ok(menuIds);
        }

        /// <summary>
        /// 获取用户权限标识列表
        /// </summary>
        [HttpGet("permissions/{userId}")]
        public async Task<ApiResult<object>> GetUserPermissions(int userId)
        {
            var permissions = await _menuService.GetUserPermissionsAsync(userId);
            return ApiResult<object>.Ok(permissions);
        }
    }
}